package com.trg.job.service.impl;

import com.trg.job.service.FetchDataService;
import com.trg.job.utils.HttpClientUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;


@Component
public class FetchDataServiceImpl implements FetchDataService {

    private static final String EMESSAGE_URL = "http://trg-msg/controller/IMailController/sendHtmlMail/";

    private static final String subject = "常识题每日消息推送！";


    @Value("${mail.sendUser}")
    private String sendUser;


    @Resource
    RestTemplate restTemplate;

    /**
     * 地址：https://www.offcn.com/xingce/2021/1130/77839.html
     */

    @Override
    public void getZg() {
        int num = 79289;
        LocalDate of = LocalDate.of(2021, 12, 01);
        String url = "https://www.offcn.com/xingce/yyyy/md/id.html";
        LocalDate now = LocalDate.now();

        int yyyy = now.getYear();
        int dayOfMonth = now.getDayOfMonth();
        String day = dayOfMonth < 10 ? 0 + "" + dayOfMonth : dayOfMonth + "";
        int monthValue = now.getMonthValue();
        String mon = monthValue < 10 ? 0 + "" + monthValue : monthValue + "";

        int i = (int) (now.toEpochDay() - of.toEpochDay());

        num = num + i;

        url = url.replaceAll("yyyy", yyyy + "").replaceAll("md", mon + "" + day + "").replaceAll("id", num + "");
        System.out.printf("当前调用地址：" + url);
        HashMap<String, String> map = new HashMap<>();
        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
        postParameters.add("subject", subject);
        postParameters.add("to", sendUser);


        String s = HttpClientUtil.doGet(url, map);
        if (s != null) {
            //.Jsoup解析html
            Document document = Jsoup.parse(s);
            //像js一样，通过class 获取列表下的所有博客
            Elements postItems = document.getElementsByClass("offcn_shocont");
            String msg = postItems.toString();

            String content = msg;
            postParameters.add("content", content);
            restTemplate.postForObject(EMESSAGE_URL, postParameters, String.class);
        } else {
            postParameters.add("content", "今天没有内容哦！");
            restTemplate.postForObject(EMESSAGE_URL, postParameters, String.class);
        }
    }


}
